package com.cognizant.app.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.cognizant.app.LaunchActivity;
import com.cognizant.app.R;
import com.cognizant.app.utils.UrlParseUtil;
import com.cognizant.app.wiget.TitleLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class QRCodeScanActivity extends BaseActivity implements QRCodeView.Delegate {

    private static final String TAG = QRCodeScanActivity.class.getName();
    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;
    private static final int TARGET_PAGE = 1;
    @BindView(R.id.zxingview)
    protected ZXingView mZXingView;
    @BindView(R.id.qrcodescan_title)
    protected TitleLayout qrcodescan;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mZXingView.setDelegate(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qrcode_scan;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        qrcodescan.setTitle("Scan");
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        //mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZXingView.startSpotAndShowRect(); // 显示扫描框，并且延迟0.5秒后开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i(TAG, "result:" + result);
        vibrate();
        Intent intent = new Intent(this, LaunchActivity.class);
        intent.putExtra("targetPage", TARGET_PAGE);
        startActivity(intent);
        Map<String, String> mapRequest = UrlParseUtil.URLRequest(result);
        Toast.makeText(this, mapRequest.get("meetingid"), Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(mapRequest.get("meetingid"));
        finish();
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
    }

}
